package com.finalBlog.util;

import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.finalBlog.common.Dic;
import com.finalBlog.model.Adminuser;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.ehcache.CacheKit;

/**
 * 类/接口信息描述:
 *
 * @author dengxc
 *
 */
public class CookieTool {
	/**
	* 方法描述：添加cookie 
	*
	* @param response
	* @param domain 域名
	* @param path 路径
	* @param isHttpOnly 是否仅http（即在客户端浏览器通过js是无法获取的）
	* @param name cookie 键
	* @param value cookie 值
	* @param maxAge cookie存放的时间(以秒为单位,假如存放三天,即3*24*60*60; 如果值为0,cookie将随浏览器关闭而清除)
	*/
	public static void addCookie(HttpServletResponse response, 
			String domain, String path, boolean isHttpOnly, 
			String name, String value, int maxAge) {
		Cookie cookie = new Cookie(name, value);
		// 所在域：比如a1.4bu4.com 和 a2.4bu4.com 共享cookie
		if(StrKit.notBlank(domain)){
			cookie.setDomain(domain);			
		}
		// 设置cookie所在路径
		cookie.setPath("/");
		if(null != path && !path.isEmpty()){
			cookie.setPath(path);				
		}
		// 是否只读
		cookie.setHttpOnly(isHttpOnly);
		// 设置cookie的过期时间
		if (maxAge > 0){
			cookie.setMaxAge(maxAge);
		}
		// 添加cookie
		response.addCookie(cookie);
	}
	public static void removeUserCookie(HttpServletRequest request, HttpServletResponse response,Adminuser user){
		addCookie(response, null, "/", true, Dic.cookie_uid, null, 0);
	}
	public static void addUsercookie(HttpServletRequest request, HttpServletResponse response,Adminuser user,boolean remmenber){
		int reage = 0;
		if(remmenber)
			reage = Dic.remember_date;
		try {
			String username = user.getUsername();
			addCookie(response, "", "/", false, Dic.cookie_uname, URLEncoder.encode(username, "UTF-8"), reage);//登陆名cookie
			String nickname = user.getNickname();
			addCookie(response, "", "/", false, Dic.cookie_nickname, URLEncoder.encode(nickname, "UTF-8"), reage);//昵称cookie
		} catch (Exception e) {
			e.printStackTrace();
		}
		String username = user.getUsername();//唯一用户名
		Long timestamp = new Date().getTime();//登陆时间戳
		String ips = CommonTools.getIP(request);//登陆ip
		String userAgent = request.getHeader("User-Agent");//浏览器User-Agent
		StringBuffer sb = new StringBuffer();
		sb.append(username).append("#").append(timestamp).append("#").append(ips).append("#").append(userAgent);
		String uid = CryptTool.getInstance().encryptAES(sb.toString(), Dic.cookie_key);//加密用户信息添加到cookike
		addCookie(response, "", "/", true, Dic.cookie_uid, uid, reage);
	}
	
	public static Adminuser getCurrentUser(HttpServletRequest request){
		Map<String, String> cookiemap = CommonTools.getCookieMap(request);
		if(cookiemap.containsKey(Dic.cookie_uid)){
			String uid = cookiemap.get(Dic.cookie_uid);
			String uinfo = CryptTool.getInstance().decryptAES(uid, Dic.cookie_uid);
			if(StrKit.notBlank(uinfo)&&uinfo.indexOf("#")!=-1){
				String str[] = uinfo.split("#");
				if(str.length!=4){
					return null;
				}
				String username = str[0];
				Long logintime = Long.parseLong(str[1]);
				String ip = str[2];
				String useragent = str[3];
				Date begin = new Date();
				begin.setTime(logintime);
				if(ip.equals(CommonTools.getIP(request))&&useragent.equals(request.getHeader("User-Agent"))&&CommonTools.getDateDaySpace(begin,new Date())<7){
					return CacheKit.get(Dic.cache_system, username);
				}
			}
		}
		return null;
	}
}
